package com.lz.ovuola.util.redis.cluster;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.Serializable;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.stereotype.Component;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

@Component("hessianSerializer")
public class HessianSerializer implements RedisSerializer<Serializable> {

	@Override
	public byte[] serialize(Serializable t) throws SerializationException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		HessianOutput hessianOutput = new HessianOutput(baos);
		try {
			hessianOutput.writeObject(t);
		} catch (IOException e) {
			throw new SerializationException(e.getMessage());
		} finally {
			try {
				hessianOutput.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			close(baos);

		}
		return baos.toByteArray();
	}

	@Override
	public Serializable deserialize(byte[] bytes) throws SerializationException {
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
		HessianInput hessianInput = new HessianInput(bais);
		try {
			return (Serializable) hessianInput.readObject();
		} catch (IOException e) {
			throw new SerializationException(e.getMessage());
		} finally {
			close(bais);
		}
	}

	private void close(Closeable io) {
		try {
			io.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
